/*
  This is a test client for messaging, that will eventually be
  adapted for use in signalling the HD recorders at the UTas
  VLBI observatories.

*/

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>

#define BUFFSIZE 10000
void Die(char *mess, int sock) { perror(mess); close(sock); exit(1); }

/* 
   The main routine determines the message that is to be sent,
   tries to establish a connection, and sends the message.
*/
int main(int argc, char *argv[]) {
  int sock;
  struct sockaddr_in mesgserver;
  char buffer[BUFFSIZE],tag[BUFFSIZE],failmsg[BUFFSIZE],tmp[BUFFSIZE];
  unsigned int mesglen,taglen;
  int received = 0;
  struct hostent *chost=NULL;
  
  if (argc != 4) {
    fprintf(stderr, "USAGE: %s <server_ip> <word> <port>\n",argv[0]);
    exit(1);
  }
  /* Create the TCP socket */
  close(sock);
  if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
    Die("Failed to create socket",sock);
  }
  /* lookup the host */
  chost=gethostbyname(argv[1]);
  if (chost==NULL){
    Die("Failed to get IP address of host",sock);
  }
  
  /* Construct the server sockaddr_in structure */
  memset(&mesgserver, 0, sizeof(mesgserver));       /* Clear struct */
  mesgserver.sin_family = AF_INET;                  /* Internet/IP */
  bcopy((char*)chost->h_addr,
	(char*)&mesgserver.sin_addr.s_addr,
	chost->h_length);                           /* IP address */
/*   mesgserver.sin_addr.s_addr = inet_addr(chost->h_addr);  /\* IP address *\/ */
  mesgserver.sin_port = htons(atoi(argv[3]));       /* server port */
  /* Establish connection */
  if (connect(sock,
	      (struct sockaddr *) &mesgserver,
	      sizeof(mesgserver)) < 0) {
    Die("Failed to connect with server",sock);
  }

  /* Send the word to the server */
  mesglen = strlen(argv[2]);
  fprintf(stdout,"Sending message %s (length %d)\n",argv[2],mesglen);
  if (send(sock, argv[2], mesglen, 0) != mesglen) {
    Die("Mismatch in number of sent bytes",sock);
  }

  /* Receive the confirmation back from the server */
  /*   fprintf(stdout, "Received: "); */
  if ((received=recv(sock,buffer,BUFFSIZE-1,MSG_WAITALL))<1){
    Die("Failed to receive confirmation message from server",sock);
  } else {
    do {
      fprintf(stdout,"received %d bytes\n",received);
      fprintf(stdout,"%s\n",buffer);
    } while ((received=recv(sock,buffer,BUFFSIZE-1,MSG_WAITALL))>0);
    /* if (strcmp(buffer,"<succ />")==0){ /\* we've got a successful response *\/ */
    /*   fprintf(stdout,"request accepted\n"); */
    /* } else if (sscanf(buffer,"<status>%[^<]</status>",tmp)==1){ */
    /*   fprintf(stdout,"status returned:\n%s\n",tmp); */
    /* } else { */
    /*   sscanf(buffer,"<fail>%[^<]</fail>",failmsg); */
    /*   fprintf(stdout,"request failed: %s\n",failmsg); */
    /* } */
  }
  close(sock);
  exit(0);
}
